package com.ruoyi.web.task;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.web.domain.vo.ResultVo;
import com.ruoyi.web.mapper.MesLingCompareMapper;
import com.ruoyi.web.mapper.ReportMapper;
import com.ruoyi.web.service.MesLingCompareService;
import com.ruoyi.web.vo.MesLingCompare;
import com.ruoyi.web.vo.Report;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务调度
 * @author ruoyi
 */
@Component("lingTask")
public class LingTask {
    private static final Logger logger = LoggerFactory.getLogger(LingTask.class);
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private MesLingCompareService mesLingCompareService;
    @Resource
    private MesLingCompareMapper mesLingCompareMapper;

    // 获取用纸令数
    public void getLing(){
        logger.info("执行方法：lingTask.getLing()");
        // 获取前时间
        Calendar calendar = Calendar.getInstance();
        // 将时间往前推12小时
        calendar.add(Calendar.HOUR_OF_DAY, -12);
        int yearc = calendar.get(Calendar.YEAR);
        int monthc = calendar.get(Calendar.MONTH) + 1;
        int dayc = calendar.get(Calendar.DATE);
        // 获取当前时间
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DATE);
        int hour= cal.get(Calendar.HOUR_OF_DAY);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 定义开始截止时间
        Date beginTime = null;
        Date endTime = null;
        // 判断是早上七点还是下午七点
        if(hour == 7){
            // 早上七点，需要查询的数据范围为，昨天下午七点半至早上七点半
            try {
                beginTime = dateFormat.parse(yearc + "-" + monthc + "-" + dayc + " 19:30:00");
                endTime = dateFormat.parse(year + "-" + month + "-" + day + " 07:30:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {
            // 下午七点，需要查询的数据范围为，早上七点半至下午七点半
            try {
                beginTime = dateFormat.parse(yearc + "-" + monthc + "-" + dayc + " 07:30:00");
                endTime = dateFormat.parse(year + "-" + month + "-" + day + " 19:30:00");
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        // 保存数据的合集
        ArrayList<MesLingCompare> compareList = new ArrayList<>();

        // 查询上次实际用纸张数
        List<MesLingCompare> mesLingCompares = mesLingCompareMapper.selectUpMesLingCompare();
        Map<String, String> map = new HashMap<>();
        if(mesLingCompares.size() > 0){
            map = mesLingCompares.stream().collect(Collectors.toMap(MesLingCompare::getMachineId, MesLingCompare::getRealityZhang));
        }

        // 轮转机台是固定的7个，分别调用不通的接口获取实际用纸令数
        MesLingCompare mesLingCompare1 = createMesLingCompare("7", "一车间",
                "c3fd0c8cbabb4048872b97c3b5f5c590", "轮转（614）1号机", beginTime, endTime);
        // 根据时间和机台查询预计用纸令数
        getReportLing(beginTime, endTime, "c3fd0c8cbabb4048872b97c3b5f5c590", mesLingCompare1);
        // 获取实际用纸令数
        JSONObject jsonObject = putData(beginTime, endTime);
        ResultVo resultVo1 = getRealityZhang(jsonObject, "dataDevice5");
        resultDate(mesLingCompare1, resultVo1, "c3fd0c8cbabb4048872b97c3b5f5c590", map);

        MesLingCompare mesLingCompare2 = createMesLingCompare("7", "一车间",
                "25f60ece72b74169bc19241435746f0a", "轮转（614）2号机", beginTime, endTime);
        // 根据时间和机台查询预计用纸令数
        getReportLing(beginTime, endTime, "25f60ece72b74169bc19241435746f0a", mesLingCompare2);
        // 获取实际用纸令数
        JSONObject jsonObject2 = putData(beginTime, endTime);
        ResultVo resultVo2 = getRealityZhang(jsonObject2, "dataDevice6");
        resultDate(mesLingCompare2, resultVo2, "25f60ece72b74169bc19241435746f0a", map);

        MesLingCompare mesLingCompare3 = createMesLingCompare("7", "一车间",
                "c4d9e7770e3d4c928871ae2b9524e632", "轮转（614）3号机", beginTime, endTime);
        // 根据时间和机台查询预计用纸令数
        getReportLing(beginTime, endTime, "c4d9e7770e3d4c928871ae2b9524e632", mesLingCompare3);
        // 获取实际用纸令数
        JSONObject jsonObject3 = putData(beginTime, endTime);
        ResultVo resultVo3 = getRealityZhang(jsonObject3, "dataDevice7");
        resultDate(mesLingCompare3, resultVo3, "c4d9e7770e3d4c928871ae2b9524e632", map);

        MesLingCompare lingCompare1 = createMesLingCompare("10", "四车间",
                "fa8b4dca36b24fbc8c6de4b1d11e091e", "轮转（M700)1号机", beginTime, endTime);
        // 根据时间和机台查询预计用纸令数
        getReportLing(beginTime, endTime, "fa8b4dca36b24fbc8c6de4b1d11e091e", lingCompare1);
        // 获取实际用纸令数
        JSONObject jsonObject4 = putData(beginTime, endTime);
        ResultVo resultVo4 = getRealityZhang(jsonObject4, "dataDevice4");
        resultDate(lingCompare1, resultVo4, "fa8b4dca36b24fbc8c6de4b1d11e091e", map);

        MesLingCompare lingCompare2 = createMesLingCompare("10", "四车间",
                "b1517d9e367f4323852f1a2e984190c6", "轮转（M700)2号机", beginTime, endTime);
        // 根据时间和机台查询预计用纸令数
        getReportLing(beginTime, endTime, "b1517d9e367f4323852f1a2e984190c6", lingCompare2);
        // 获取实际用纸令数
        JSONObject jsonObject5 = putData(beginTime, endTime);
        ResultVo resultVo5 = getRealityZhang(jsonObject5, "dataDevice1");
        resultDate(lingCompare2, resultVo5, "b1517d9e367f4323852f1a2e984190c6", map);

        MesLingCompare lingCompare3 = createMesLingCompare("10", "四车间",
                "5ce9c01407214812904ebbce9c405830", "轮转（M700)3号机", beginTime, endTime);
        // 根据时间和机台查询预计用纸令数
        getReportLing(beginTime, endTime, "5ce9c01407214812904ebbce9c405830", lingCompare3);
        // 获取实际用纸令数
        JSONObject jsonObject6 = putData(beginTime, endTime);
        ResultVo resultVo6 = getRealityZhang(jsonObject6, "dataDevice3");
        resultDate(lingCompare3, resultVo6, "5ce9c01407214812904ebbce9c405830", map);

        MesLingCompare lingCompare4 = createMesLingCompare("10", "四车间",
                "325eb4a641ef4d5fb1d42d275d607e21", "轮转（M700)4号机", beginTime, endTime);
        // 根据时间和机台查询预计用纸令数
        getReportLing(beginTime, endTime, "325eb4a641ef4d5fb1d42d275d607e21", lingCompare4);
        // 获取实际用纸令数
        JSONObject jsonObject7 = putData(beginTime, endTime);
        ResultVo resultVo7 = getRealityZhang(jsonObject7, "dataDevice2");
        resultDate(lingCompare4, resultVo7, "325eb4a641ef4d5fb1d42d275d607e21", map);

        // 数据汇总
        compareList.add(mesLingCompare1);
        compareList.add(mesLingCompare2);
        compareList.add(mesLingCompare3);
        compareList.add(lingCompare1);
        compareList.add(lingCompare2);
        compareList.add(lingCompare3);
        compareList.add(lingCompare4);
        // 保存数据
        mesLingCompareService.saveBatch(compareList);

        logger.info("执行多参方法：lingTask.getLing()====结束====");
    }

    // 创建实体类（用纸令数对比表）
    public MesLingCompare createMesLingCompare(String workshopId, String workshopName, String machineId, String machineName,
                                               Date beginTime, Date endTime){
        MesLingCompare lingCompare = new MesLingCompare();
        lingCompare.setWorkshopId(workshopId);
        lingCompare.setWorkshopName(workshopName);
        lingCompare.setMachineId(machineId);
        lingCompare.setMachineName(machineName);
        lingCompare.setBeginTime(beginTime);
        lingCompare.setEndTime(endTime);
        lingCompare.setCreateTime(new Date());
        return lingCompare;
    }

    // 创建三方接口入参
    public JSONObject putData(Date beginTime, Date endTime){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pageNum", 1);
        jsonObject.put("pageSize", 10);
        jsonObject.put("beginTime", beginTime);
        jsonObject.put("endTime", endTime);
        return jsonObject;
    }

    // 根据时间和机台查询预计用纸令数
    public MesLingCompare getReportLing(Date beginTime, Date endTime, String machineId, MesLingCompare mesLingCompare){
        Report report = new Report();
        report.setBeginDate(beginTime);
        report.setEndDate(endTime);
        report.setMachineId(machineId);
        Report report1 = reportMapper.selectReportLing(report);
        if(report1 != null){
            if(report1.getExpectLing() == null) report1.setExpectLing("0");
            mesLingCompare.setExpectLing(report1.getExpectLing());
            mesLingCompare.setReportPeople(report1.getCreateBy());
        }else {
            mesLingCompare.setExpectLing("0");
        }
        return mesLingCompare;
    }

    // 计算
    public MesLingCompare resultDate(MesLingCompare mesLingCompare, ResultVo resultVo, String machineId, Map<String, String> map){
        String total = "0";
        JSONObject from = JSONObject.from(resultVo);
        mesLingCompare.setResultData(from.toJSONString());
        if(resultVo.getSuccess() != null && resultVo.getSuccess()){
            List<ResultVo.dataInfo> data = resultVo.getData();
            if(data != null){
                total = data.get(0).getTotal() == null ? "0" : data.get(0).getTotal();
            }
        }else {
            mesLingCompare.setErr(resultVo.getMsg());
        }
        mesLingCompare.setRealityZhang(total);
        // 计算令数 = （当前实际用纸张数 - 上次实际用纸张数） / 1000
        // 获取上次实际用纸张数
        BigDecimal decimal = map.get(machineId) == null ? new BigDecimal("0") : new BigDecimal(map.get(machineId));
        BigDecimal divide = new BigDecimal(total).subtract(decimal).divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
        mesLingCompare.setRealityLing(divide.stripTrailingZeros().toPlainString());
        return mesLingCompare;
    }

    // 获取实际用纸张数
    public ResultVo getRealityZhang(JSONObject jsonObject, String url) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        okhttp3.RequestBody body = okhttp3.RequestBody.create(mediaType, jsonObject.toJSONString());
        Request request = new Request.Builder()
                .url("http://192.168.3.176:30010/idm-api/" + url)
                .method("POST", body)
                .addHeader("appId", "idm-NWqmC9")
                .addHeader("appSecret", "23718895684531216411")
                .addHeader("Content-Type", "application/json")
                .build();
        ResultVo resultVo = new ResultVo();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            String result = response.body().string();
            JSONObject object = JSONObject.parseObject(result);
            resultVo = object.toJavaObject(ResultVo.class);
            return resultVo;
        } catch (IOException e) {
            resultVo.setSuccess(false);
            resultVo.setMsg(e.getMessage());
            return resultVo;
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }
}
